package de.mmis.core.base.abstracttree;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.apache.log4j.Logger;

import de.mmis.core.base.Toolbox;
import de.mmis.core.base.abstracttree.LeafNode.Encoding;

public class SimpleTreeWriter implements TreeWriter {

	private final static Logger LOGGER = Logger
			.getLogger(SimpleTreeWriter.class);

	@Override
	public byte[] writeAbstractTree(Tree abstractTree) {
		ByteArrayOutputStream baos = new ByteArrayOutputStream();
		try {
			writeAbstractTree(abstractTree, baos);
		} catch (IOException e) {
			LOGGER.error("unexpected IOException while writing in byte array",
					e);
		}
		return baos.toByteArray();
	}

	@Override
	public void writeAbstractTree(Tree at, OutputStream out) throws IOException {
		switch (at.getType()) {
		case LEAF:
			if (((LeafNode) at).getEncoding() != Encoding.Token) {
				out.write('[');
				out.write(Toolbox.toUTF8Bytes(((LeafNode) at).getEncoding()
						.toString()));
				out.write(']');
			}
			out.write(((LeafNode) at).getData());
			break;
		case INNER:
			out.write('(');
			boolean first = true;
			for (Tree e : ((InnerNode) at)) {
				if (!first)
					out.write(' ');
				first = false;
				writeAbstractTree(e, out);
			}
			out.write(')');
			break;
		}
	}
}
